package com.tools.genxsd;

import com.tools.genxsd.util.ExcelUtil;
import com.tools.genxsd.util.FilePathUtil;
import com.tools.genxsd.util.PatternUtil;

import java.io.File;

import static cn.hutool.core.text.StrPool.BACKSLASH;
import static cn.hutool.core.text.StrPool.SLASH;
import static com.tools.genxsd.constant.SysConstant.*;

/**
 * 根据Excel配置生成对应的xsd文件.
 *
 * @author: zhoubin
 * @date: 2022/11/11
 */
public class XsdGenerate {

    public static void main(String[] args) throws Exception {
        File file = new File(FilePathUtil.getFilePath());

        createXsdDir(FilePathUtil.getFilePath());

        if (file.isDirectory()) {
            File[] files = file.listFiles();

            for (File inFile : files) {

                String fileName = inFile.getName();
                if (inFile.isDirectory()
                        || fileName.startsWith(FILE_TEP)
                        || (!fileName.endsWith(SUF_XLSX) && !fileName.endsWith(SUF_XLS))) {

                    System.out.println("跳过文件: " + fileName);
                    continue;
                }

                // 将Excel解析成节点对象
                ExcelUtil.praseExcelToXsdElement(inFile);
            }
        } else if (PatternUtil.isExcel(file.getName())) {
            // 将Excel解析成节点对象
            ExcelUtil.praseExcelToXsdElement(file);
        }

        System.out.println("xsd生成成功！");
    }

    /**
     * 在文件平级中创建xsd目录存放xsd文件
     * @param excelPath
     */
    public static void createXsdDir(String excelPath) {

        File file = null;
        if (excelPath.endsWith(SUF_XLSX) || excelPath.endsWith(SUF_XLS)) {
            String split = excelPath.contains(SLASH) ? SLASH : BACKSLASH;

            int index = excelPath.lastIndexOf(split);
            file = new File(excelPath.substring(0, index + 1) + XSD);
        } else {
            file = new File(excelPath + XSD);
        }

        if (!file.exists()) {
            file.mkdir();
        }
    }
}
